import { useEffect } from 'react';

const { default: useStore } = require('@/store');
const { getToken } = require('@/utils');
const { message } = require('antd');
const { useNavigate } = require('react-router-dom');

export default function AuthComponent({ children }) {
  const { loginStore } = useStore();
  const nav = useNavigate();
  useEffect(() => {
    const token = getToken();
    if (!token) {
      nav('/login', { replace: true });
    } else {
      const isTokenValid = async () => {
        const result = await loginStore.checkToken(token);
        if (!result?.isValid) {
          message.error('token失效，请重新登录');
          nav('/login', { replace: true });
        }
      };
      isTokenValid();
    }
  }, []);

  return children;
}
